package com.gitee.deament.server.core.data.thread;

import com.gitee.deament.server.config.SystemConfig;
import com.gitee.deament.server.core.data.DBInnerData;
import com.gitee.deament.server.core.data.datatype.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 过期键 线程
 *
 * @author deament
 */
public class ExpirKeyThread {
    static Logger logger = LoggerFactory.getLogger(ExpirKeyThread.class);

    private ExpirKeyThread() {
        //禁止new
    }

    private static Thread runThread;

    public static void start() {
        if (runThread != null) {
            runThread.interrupted();
        }
        runThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                        DBInnerData[] dbInnerData = SystemConfig.dbData.getDBInnerData();
                        for (int i = 0; i < dbInnerData.length; i++) {
                            ConcurrentHashMap<String, Value<?>> data = dbInnerData[i].getData();
                            Enumeration<String> keys = data.keys();
                            while (keys.hasMoreElements()) {
                                String key = keys.nextElement();
                                Date expirDateTime = data.get(key).getExpirDateTime();
                                if (expirDateTime != null && expirDateTime.compareTo(new Date()) <= 0) {
                                    data.remove(key);
                                }
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("{}", e);
                    }
                }
            }
        });


    }
}
